from flask import Blueprint, render_template, jsonify, request
from App.models import Department, Employee

second = Blueprint('second', __name__)


@second.route('/sec')
def sec():
    return render_template('index.html', msg='今天天气很好啊！')


@second.route('/depts')
def get_departments():
    depts = Department.query.all()
    return jsonify([dept.to_dict() for dept in depts])


@second.route('/emps/')
def get_employees():
    key = request.args.get('key', '')
    dept_id = int(request.args.get('dept_id', 0))
    if dept_id:
        emps = Employee.query(Employee).filter(Employee.name.contains(key),
                                               Employee.department_id == dept_id).all()
    else:
        emps = Employee.query.with_entities(Employee).filter(Employee.name.contains(key)).all()
    # return jsonify([d.to_dict(("id", "idcard", "birthdate")) for d in emps])
    return jsonify([d.to_dict() for d in emps])


@second.route('/content/')
def content1():
    return render_template('content1.html')


@second.route('/ajax1/')
def get_content():
    return render_template('ajax-basic.html')


@second.route('/emps1/')
def get_emps_ajax():
    key = request.args.get('key', '')
    table_header = """ 
    <table border ="1">
        <tr>
            <th>ID</th><th>姓名</th><th>地址</th><th>工资</th>
        </tr>
    """
    emps = Employee.query.filter(Employee.name.contains(key)).all()
    rows = ""
    for emp in emps:
        rows += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>".format(emp.id, emp.name, emp.address,
                                                                               emp.salary)
    table_footer = "</table>"

    return table_header + rows + table_footer


@second.route('/ajax_query1/')
def get_ajax_query1():
    return render_template('ajax_query1.html')


@second.route('/ajax_json/')
def get_emps_json():
    return render_template('ajax_query_json.html')


@second.route('/ajax_vue/')
def get_emps_vue():
    # return 'test!'
    return render_template('ajax_vue.html')


@second.route('/ajax_element/')
def get_emps_element():
    # return 'test!'
    return render_template('ajax_element.html')


@second.route('/get_datas/')
def get_datas():
    xaxis = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '玖月', '十月', '十一月', '十二月']
    series1 = [6660837.40, 4300635.00, 6292235.48, 3910364.61, 4458285.49, 4259013.90, 4905845.24, 4752580.43,
               5398837.07, 4957148.53, 5282152.66, 6143419.35]
    series2 = [8083314.33, 5425632.11, 8782690.08, 4920440.81, 5495647.80, 5217495.37, 6069051.91, 5875419.64,
               6539587.13, 6155467.76, 6445012.65, 7393449.53]
    datas = {
        'xaxis': xaxis,
        'series1': series1,
        'series2': series2,
    }
    # print(datas)
    return jsonify(datas)
    # return render_template('ajax_element.html')


@second.route('/vue_echarts/')
def vue_echarts():
    # return 'test!'
    return render_template('vue_echarts.html')
